//
//  YZMGridView.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/28.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMGridView.h"
#import "YZMAppStyle.h"
#import "YZMGridMoneyModel.h"
#import <Masonry/Masonry.h>
#import "NSNumber+Utils.h"
#import "UIImage+Utils.h"
#import "YZMStockBuyModel.h"

static const int grid_view_column = 4;


@implementation YZMGridView{
    
    NSMutableArray *_buttonList;
    NSArray *_dataList;
    
    NSInteger _defaultSelectedIndex;
}

@synthesize dataList = _dataList;

- (id)init{
    
    self = [super init];
    
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        _buttonList = [NSMutableArray array];
        _defaultSelectedIndex = -1;
    }
    
    return self;
}

#pragma mark -- Public Method

- (void)setDataList:(NSArray *)dataList{
    
   
    //视图清理
    [_buttonList removeAllObjects];
    _dataList = [NSArray arrayWithArray:dataList];
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    
    //视图重建
//    [YZMAppStyle addLineViewWithParentView:self color:[YZMAppStyle colorForSplitLine]];
//    [YZMAppStyle addTopLineViewWithParentView:self color:[YZMAppStyle colorForSplitLine]];
    [YZMAppStyle addLeftLineViewWithParentView:self color:[YZMAppStyle colorForSplitLine]];
    UIView *lastView = nil;
    NSInteger rows = [self rows];
    NSInteger row = _dataList.count % grid_view_column; //每行个数
   
    if (rows > 1 || (rows == 1 && row == 0)) {
        [YZMAppStyle addTopLineViewWithParentView:self color:[YZMAppStyle colorForSplitLine]];
    } else {
        UIView* topLine = [YZMAppStyle splitLine];
        [self addSubview:topLine];
        [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self);
            make.height.equalTo(@0.5);
            make.width.equalTo(self).dividedBy(grid_view_column / (double)row);
        }];
    }
    
    if (row == 0) {
        [YZMAppStyle addLineViewWithParentView:self color:[YZMAppStyle colorForSplitLine]];
    } else {
        UIView* bottomLine = [YZMAppStyle splitLine];
        [self addSubview:bottomLine];
        [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.equalTo(self);
            make.height.equalTo(@0.5);
            make.width.equalTo(self).dividedBy(grid_view_column / (double)row);
        }];
    }
    
    NSInteger defaultIndex = -1;
    
    for (int i=0; i<rows; i++) {
        
        UIView *bgView = [UIView new];
        bgView.backgroundColor = [UIColor clearColor];
        [self addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.left.right.equalTo(self);
            
            if (lastView) {
                
                maker.top.equalTo(lastView.mas_bottom);
                
            }else{
                
                maker.top.equalTo(self);
            }
        }];
        
        /*加底部横线*/
        if (i < rows-1) {
         
            UIView *line = [YZMAppStyle splitLine];
            line.backgroundColor = [YZMAppStyle colorForSplitLine];
            [bgView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *maker){
                
                maker.bottom.left.right.equalTo(bgView);
            }];
        }
        
        UIView *jLastView = nil;
        
        for (int j=0; j< grid_view_column; j++) {
            
            NSInteger dataIndex = i*grid_view_column + j;

            if (dataIndex >= _dataList.count) {  /*占位单元格*/
//
//                /*单元格 背景视图*/
//                UIView *unableView = [UIView new];
//                unableView.backgroundColor = [UIColor clearColor];
//                [bgView addSubview:unableView];
//                [unableView mas_makeConstraints:^(MASConstraintMaker *maker){
//
//                    maker.top.bottom.equalTo(jLastView);
//                    maker.left.equalTo(jLastView.mas_right);
//                    maker.width.equalTo(jLastView);
//
//                }];
//
//                /*横线*/
//                UIView *unableLine = [YZMAppStyle splitLine];
//                unableLine.backgroundColor = [YZMAppStyle colorForSplitLine];
//                [unableView addSubview:unableLine];
//                [unableLine mas_remakeConstraints:^(MASConstraintMaker *maker){
//
//                    maker.height.mas_equalTo(0.5);
//                    maker.width.equalTo(unableView).dividedBy(5);
//                    maker.centerX.centerY.equalTo(unableView);
//                }];
//
//                jLastView = unableView;
            
            }else{ /*非占位单元格*/
                
                NSString *moneyString;
                if (self.type == YZMGridViewTypePrincipal) {
                    YZMStockBuyModel *buymodel = dataList[dataIndex];
                    moneyString = buymodel.principal;
                }else{
                    YZMGridMoneyModel *data = dataList[dataIndex];
                    if (data.defaultFlag) {
                        defaultIndex = dataIndex;
                    }
                    moneyString  = @(data.money).unitString;
                }
                
                UIButton *button = [UIButton new];
                
                
                
                [button setTitle:moneyString forState:UIControlStateNormal];
                [button setTitleColor:[YZMAppStyle colorForGrayText] forState:UIControlStateNormal];
                [button setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateSelected];
                [button setBackgroundColor:[UIColor clearColor]];
                [button setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle buttonSelectedColor]] forState:UIControlStateSelected];
                [button.titleLabel setFont:[YZMAppStyle largeSizeFont]];
                button.tag = dataIndex;
                [button addTarget:self action:@selector(clickToChoose:) forControlEvents:UIControlEventTouchUpInside];
                [bgView addSubview:button];
                [_buttonList addObject:button];
                [button mas_makeConstraints:^(MASConstraintMaker *maker){
                    
                    maker.bottom.equalTo(bgView).offset(-1);
                    
                    
                    if (j == 0) {
                        
                        maker.height.mas_equalTo(54);
                        maker.left.equalTo(bgView);
                        maker.width.equalTo(bgView).dividedBy(grid_view_column);
                        if (i == 0) {
                            maker.top.equalTo(bgView).offset(1);
                        }else{
                            
                            maker.top.equalTo(bgView);
                        }
                        
                    }else{
                        maker.top.bottom.equalTo(jLastView);
                        maker.left.equalTo(jLastView.mas_right);
                        maker.width.equalTo(jLastView);
                    }
                    
                }];
                
                UIView *ivLineRight = [UIView new];
                ivLineRight.backgroundColor = [YZMAppStyle colorForSplitLine];
                [button addSubview:ivLineRight];
                [ivLineRight mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.bottom.right.equalTo(button);
                    make.width.mas_equalTo(0.5);
                }];
                jLastView = button;
            }
            
//            if (i == rows -1 && j < grid_view_column-1) {
//                
////                UIView *cLine = [YZMAppStyle splitLine];
////                cLine.backgroundColor = [YZMAppStyle colorForSplitLine];
////                [self addSubview:cLine];
////                [cLine mas_remakeConstraints:^(MASConstraintMaker *maker){
////
////                    maker.top.bottom.equalTo(self);
////                    maker.width.mas_equalTo(0.5);
////                    maker.centerX.equalTo(jLastView.mas_right);
////                }];
//            }
        }
        
        lastView = bgView;
    }
    
    [self mas_updateConstraints:^(MASConstraintMaker *maker){
        
        maker.bottom.equalTo(lastView);
    }];
    
    if (defaultIndex >= 0 && _defaultSelectedIndex < 0) {
        
        [self clickToChoose:_buttonList[defaultIndex]];
    }
    
    if (_defaultSelectedIndex >= 0) {
        
        /*表示之前有手动选中过*/
        if (_defaultSelectedIndex < _dataList.count) {
            
            [self clickToChoose:_buttonList[_defaultSelectedIndex] withManualFlag:NO];
        }else{
            
            [self clickToChoose:_buttonList[_dataList.count -1] withManualFlag:NO];
        }
        
    }else{
        
        if (defaultIndex >= 0) {
            
            _defaultSelectedIndex = defaultIndex;
            [self clickToChoose:_buttonList[defaultIndex] withManualFlag:NO];
            
        }else{
            
            [self clickToChoose:_buttonList[0] withManualFlag:NO];
        }
    }
}

#pragma mark -- Event Response
- (void)clickToChoose:(UIButton *)sender withManualFlag:(BOOL)manualFlag{
    
    for (UIButton *button in _buttonList) {
        
        button.selected = NO;
        button.userInteractionEnabled = YES;
    }
    
    sender.selected = YES;
    
    if (manualFlag) {
        
        _defaultSelectedIndex = sender.tag;
    }
    
    if (self.clickAction) {
        
        self.clickAction(sender.tag, _dataList[sender.tag]);
    }
}

- (void)clickToChoose:(UIButton *)sender{
    
    [self clickToChoose:sender withManualFlag:YES];
}


#pragma mark -- Private Method


- (NSInteger)rows{
    
    return _dataList.count/grid_view_column + (_dataList.count%grid_view_column?1:0);
}

@end
